package com.example.im.ui.fragment

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.bean.UserRoom
import com.example.im.bean.EventBusData
import com.example.im.ui.activity.RoomActivity
import com.example.im.common.Constants
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.db.DatabaseStorage
import com.example.im.ui.adapter.UserRoomAdapter
import kotlinx.android.synthetic.main.fragment_friend_view_page.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FriendRoomFragment : AbstractBaseFragment<BasePresenter<*>>(),
    UserRoomAdapter.OnClickItemListener {

    var userRooms = mutableListOf<UserRoom>()
    var adapter: UserRoomAdapter? = null

    init {
        val userRooms = DatabaseStorage.getUserRoomToRoom()
            ?: arrayListOf()
        this.userRooms.addAll(userRooms)
    }

    override val layoutId: Int
        get() = R.layout.fragment_friend_view_page

    override fun initView() {

        EventBus.getDefault().register(this)

        adapter = UserRoomAdapter(activity!!, userRooms)
        adapter!!.setOnItemClickListener(this)
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = adapter
    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: EventBusData<UserRoom>) {
        if (eventBus.type ?: return != Enumerate.Handle.list_group) {
            return
        }
        when (eventBus.action ?: return) {
            Enumerate.Action.list_add ->
                adapter!!.addDataItem(eventBus.data ?: return)
            Enumerate.Action.list_delete ->
                adapter!!.removeDataItem(eventBus.data ?: return)
            else -> return
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    override fun onClickItem(view: View, position: Int) {
        val intent = Intent(activity, RoomActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_POINT, Constants.BUNDLE_T0_ROOM_POINT_1)
        intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_DATA, userRooms[position])
        activity!!.startActivity(intent)
    }

}